/**
 * BaseAction.java   1.00    2008/03/08
 * Sinyee Framework.
 * Copyright 2008-2010 SINYEE I.T. Co., Ltd. All rights reserved.
 * @author SINYEE I.T. Co., Ltd.
 */

package com.xinlu.common.resource.io;

import java.io.File;
import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.opensymphony.xwork2.util.LocalizedTextUtil;
import com.xinlu.common.log.Logger;
import com.xinlu.derek.common.BaseAction;

/**
 * 针对模块资源文件的辅助类
 * 
 */
public class ResourcesInitUtil {

	protected static Logger logger = Logger.getLogger(ResourcesInitUtil.class);

	/**
	 * 资源文件放置的包
	 */
	public static String textPathPack = "resources";

	/**
	 * 对应的action
	 */
	protected BaseAction action;

	public ResourcesInitUtil(BaseAction action) {

		this.action = action;
	}

	/**
	 * 
	 * function:加载类对应的资源文件
	 * 
	 * 
	 * @author Rain Stars Aug 5, 2009 3:24:01 PM
	 */
	public void initText() {

		String textPath = getTextPath(action.getClass().getName());

		logger.info(action.getClass() + " init [" + textPath + "] start");

		long checkStartTime = System.currentTimeMillis();

		try {
		     Resource rs =	new ClassPathResource(textPath);
		     
			if (rs.getFile().exists()) {

				File[] files =	rs.getFile().listFiles();
				
				for (int i = 0; i < files.length; i++) {
					
					//得到文件名（去掉后缀名）
					String fileName = files[i].getName().substring(0, files[i].getName().indexOf("."));
					
					LocalizedTextUtil.addDefaultResourceBundle(textPath+"/"+fileName);
					
					logger.info(action.getClass() + " init [" + files[i].getName() + "] end");
				}
				

			}
		} catch (IOException e) {

			logger.warn(action.getClass() + " init [" + textPath + "] fail, file is not found! ");
		}

		long checkTime = System.currentTimeMillis() - checkStartTime;

		logger.info(action.getClass() + " init [" + textPath + "] end, cost " + checkTime + " ms");

	}

	/**
	 * 
	 * function:根据action 类定义得到资源文件的路径
	 * 
	 * @return
	 * 
	 * @author Rain Stars Aug 5, 2009 3:22:23 PM
	 */
	public static String getTextPath(String actionClassName) {

		String textPath = null;

		String packerName = actionClassName.substring(0, actionClassName.lastIndexOf("."));

		packerName = packerName.substring(0, packerName.lastIndexOf("."));

		//textPath = packerName + ".resources" + packerName.substring(packerName.lastIndexOf(".")) + "_message";

		textPath = packerName + ".resources";
		
		return textPath.replace(".", "/");
	}
}
